package com.lsj.gulimall.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsj.gulimall.product.dao.BrandDao;
import com.lsj.gulimall.product.dao.CategoryDao;
import com.lsj.gulimall.product.entity.BrandEntity;
import com.lsj.gulimall.product.entity.CategoryEntity;
import com.lsj.gulimall.product.vo.CategoryBrandVo;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsj.common.utils.PageUtils;
import com.lsj.common.utils.Query;

import com.lsj.gulimall.product.dao.CategoryBrandRelationDao;
import com.lsj.gulimall.product.entity.CategoryBrandRelationEntity;
import com.lsj.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Resource
    BrandDao brandDao;

    @Resource
    CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增品牌与三级分类关系数据
     * @param categoryBrandVo
     */
    @Override
    public void save(CategoryBrandVo categoryBrandVo) {
        // 获取品牌
        BrandEntity brand = brandDao.selectById(categoryBrandVo.getBrandId());
        // 获取三级分类数据
        CategoryEntity category = categoryDao.selectById(categoryBrandVo.getCatelogId());

        // 新建保存品牌与三级分类关系
        CategoryBrandRelationEntity categoryBrandRelation = new CategoryBrandRelationEntity();
        categoryBrandRelation.setBrandId(categoryBrandVo.getBrandId());
        categoryBrandRelation.setBrandName(brand.getName());
        categoryBrandRelation.setCatelogId(categoryBrandVo.getCatelogId());
        categoryBrandRelation.setCatelogName(category.getName());
        this.baseMapper.insert(categoryBrandRelation);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long brandId) {
        QueryWrapper<CategoryBrandRelationEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(brandId)) {
            wrapper.eq("brand_id",brandId);
        }
        IPage<CategoryBrandRelationEntity> page = this.page(new Query<CategoryBrandRelationEntity>().getPage(params),
                wrapper);
        return new PageUtils(page);
    }

}